package com.pioneer.fationservice.helpers;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.os.AsyncTask;
import android.util.Log;

import com.pioneer.fationservice.listeners.FileDownloadListener;

/**
 * 文件下载辅助类
 * @author Mrper
 *
 */
public class FileDownloadHelper {
	/**
	 * 文件下载
	 * @param context
	 * @param fileUrl 文件下载地址
	 * @param filename 文件存储路径
	 * @param title 文件下载提示标题
	 * @param message 文件下载提示文字
	 * @param listener 文件下载监听
	 */
	public static void download(final Context context,final String fileUrl,final String filename,final String title,final String message,final FileDownloadListener listener){
		(new AsyncTask<String,Integer,Boolean>(){
			/**
			 * 下载进度框
			 */
			private ProgressDialog proDialog;
			
			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				proDialog = new ProgressDialog(context);
				proDialog.setTitle(title);
				proDialog.setMessage(message);
				proDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
				proDialog.setOnDismissListener(new OnDismissListener() {
					@Override
					public void onDismiss(DialogInterface dialog) {
						proDialog = null;
					}
				});
				proDialog.show();
				if(listener!=null) listener.fileDownloadStart();
			}
			
			@Override
			protected Boolean doInBackground(String... params) {
				try{
					HttpURLConnection httpConn = (HttpURLConnection)(new URL(fileUrl).openConnection());
					httpConn.setRequestMethod("GET");
					httpConn.setConnectTimeout(10*1000);
					httpConn.setReadTimeout(60*1000);
					httpConn.setDefaultUseCaches(false);
					httpConn.setRequestProperty("Content-Type", "application/octet-stream");
					httpConn.setRequestProperty("Accept-Ranges", "bytes");
					httpConn.setRequestProperty("Connection", "Keep-Alive");
					httpConn.setRequestProperty("Charset", "UTF-8");
					httpConn.connect();
					if(httpConn.getResponseCode() == HttpURLConnection.HTTP_OK){
						InputStream fileStream = httpConn.getInputStream();
						if(fileStream!=null){
							proDialog.setMax(httpConn.getContentLength());
							File file = new File(filename+".tmp");	
							if(file.exists()) file.delete();
							File fileParent = file.getParentFile();
							if(fileParent.isDirectory()||fileParent.mkdirs()){
								FileOutputStream fos = new FileOutputStream(file);
								int length = 0,downloadLength = 0;
								byte[] buffer = new byte[2048];
								while((length = fileStream.read(buffer,0,buffer.length))!=-1){
									fos.write(buffer,0,length);
									downloadLength += length;
									proDialog.setProgress(downloadLength);
								}
								fos.flush();
								fileStream.close();
								fos.close();
							}
							return true;
						}
					}
				}catch(Exception e){
					e.printStackTrace();
					Log.e("FileDownload", "FileDownload throws an error: "+e.getMessage());
				}
				return false;
			}
			
			@Override
			protected void onPostExecute(Boolean result) {
				super.onPostExecute(result);
				if(proDialog == null || context == null) return;
				proDialog.dismiss();
				if(listener!=null){
					if(result){
						new File(filename+".tmp").renameTo(new File(filename));
						listener.fileDownDone();
					}
					else listener.fileDownloadError();
				}
			}
			
		}).execute();
	}
	
}
